package handler

import (
	"cinema-manager/model"
	"github.com/gin-gonic/gin"
	"strconv"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	var user model.User
	model.DB.Where("username = ?", username).Find(&username)
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "登录失败",
		})
		return
	}
	if user.Password != password {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}
func UserAddRole(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	data := model.UserRole{
		Uid: uid,
		Rid: rid,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "用户添加角色成功",
	})
	return
}
func RoleAddNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := model.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "用户添加角色成功",
	})
	return
}
func UserRoleDetail(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid"))
	var userrole []model.UserRole
	model.DB.
		Table("roles").
		Select("user_roles.id as ID",
			"user_roles.uid as Uid",
			"user_roles.rid as Rid",
			"roles.role_name as RoleName").
		Joins("left join user_roles on roles.id = user_roles.rid").
		Where("user_roles.uid = ?", uid).
		Find(&userrole)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": userrole,
	})
}
func RoleNodeDetail(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))
	var rolenode []model.RoleNode
	model.DB.
		Table("nodes").
		Select("role_nodes.id as ID",
			"role_nodes.rid as Rid",
			"role_nodes.nid as Nid",
			"nodes.node_name as nodeName").
		Joins("left join role_nodes on nodes.id = role_nodes.nid").
		Where("role_nodes.rid = ?", rid).
		Find(&rolenode)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": rolenode,
	})
}
